package com.ruoyi.system.initial;

import com.ruoyi.system.domain.InfoUser;
import com.ruoyi.system.service.IInfoUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JerryLu
 * @date 2024/8/6 18:37
 * @description 坐席人员信息加载线程
 */
@Component
public class UserInfoThread {
    private final Logger logger = LoggerFactory.getLogger(UserInfoThread.class);

    private final String KEY_ALL = "ALL";

    private Map<String, String> userMap = new HashMap<>();

    @Autowired
    private IInfoUserService userService;

    // 在构造函数中初始化pattern,只编译一次
    public UserInfoThread() {
    }

    /**
     * 初始化更新各类数据信息
     *
     * @return void
     * @author JerryLu
     * @date 2024/8/15 13:04
     */
//    @Async("asyncServiceExecutor")
    public void execute() {
//        try {
        Map<String, String> map = loadUserInfoDtoMap();
        if (null == map || map.isEmpty()) {
            throw new RuntimeException("坐席人员信息加载失败");
        }
        userMap = map;
//            Thread.sleep(0);
//        } catch (InterruptedException e) {
//            // 恢复中断状态
//            Thread.currentThread().interrupt();
//            logger.warn("动态库计费模块线程加载异常: " + e.getMessage());
//        }
//        return new AsyncResult<>("");
    }

    /**
     * 根据userId获取对应坐席人员库
     *
     * @param userId
     * @return
     */
    public String getUserInfo(String userId) {
        String userInfo = userMap.get(userId);

        if (null != userInfo) {
            return userInfo;
        }
        return userMap.get(KEY_ALL);
    }

    private Map<String, String> loadUserInfoDtoMap() {
        try {
            Map<String, String> map = new HashMap<>();
            InfoUser infoUser = new InfoUser();
            List<InfoUser> userList = userService.selectInfoUserList(infoUser);
            for (InfoUser user : userList) {
//                UserInfoDto dto = loadDto(user.getUserId(), user.getUserName());
                map.put(user.getUserId(), user.getUserName());
            }
            return map;
        } catch (Throwable t) {
            logger.error(String.valueOf(t), t);
        }
        return null;
    }

//    private UserInfoDto loadDto(String userId, String userName) {
//        UserInfoDto dto = new UserInfoDto();
//        dto.setUserId(userId);
//        dto.setUserName(userName);
//
//        return dto;
//    }
}
